import axios from "axios";
import {Toast} from "mint-ui";
import Qs from "qs";
import { Loading } from 'element-ui';

// 创建axios实例,默认请求头  Content-Type: application/x-www-form-urlencoded;charset=utf-8
const service = axios.create({
    baseURL: process.env.BASE_API, // api的base_url
    timeout: 15000,// 请求超时时间
    headers: {'registType': "2"}
});

let loadingInstance ;

// request拦截器
service.interceptors.request.use(config => {
    loadingInstance = Loading.service({text:"正在加载中"});
    return config
}, error => {
})

// respone拦截器
service.interceptors.response.use(
    response => {
        /**
         * code为非200是抛错 可结合自己业务进行修改
         */
        const res = response.data

        console.log("%c request  url  ==> ", "color:blue;font-size:10px",response.config.url.replace(response.config.baseURL,""))
        console.log("%c request  data ==> ", "color:blue;font-size:10px",response.config.params)
        console.log("%c response data ==> ", "color:#909;font-size:10px",res)
        console.log("----------------------------------------------")

        if (res.retCode !== "200") {
            Toast({
                message: res.retMsg,
                iconClass: 'el-icon-circle-close-outline'
            });
        }
        loadingInstance.close();
        return res
    },
    error => {
        console.log('err', error)// for debug
        Toast({
            message: '访问失败,请检查网络',
            iconClass: 'el-icon-circle-close-outline'
        });
        loadingInstance.close();
    }
)

const ajax = {
    get(url, params, callable){
        service.get(url, {params}).then(response => {
            //当code存在切为200的时候执行业务方法
            if (!!response && !!response.retCode && response.retCode == "200") {
                callable.call(this, response.retDetail)
            }
        })
    },
    JSONPost(url, params, callable) {
        service.post(url, params).then(response => {
            //当code存在切为200的时候执行业务方法
            if (!!response && !!response.retCode && response.retCode == "200") {
                callable.call(this, response.retDetail)
            }
        })
    },
    FORMPost(url, params, callable) {
        service.post(url, Qs.stringify(params), {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(response => {
            //当code存在切为200的时候执行业务方法
            if (!!response && !!response.retCode && response.retCode == "200") {
                callable.call(this, response.retDetail)
            }
        })
    }

}

export default ajax
